<template>
  <div class="card-out-container">
    <a-form layout="inline" class="multi-line-search-form" v-if="showMore">
      <a-form-item :label="$t('sysManage.user')">
        <a-input v-model:value.trim="queryParam.staffNo" :placeholder="$t('basicData.jobNoName')" @keyup.enter="loadData" allowClear />
      </a-form-item>
      <a-form-item :label="$t('sysManage.depart')">
        <a-tree-select v-model:value="queryParam.deptId" show-search style="width: 150px;" :dropdown-style="{ maxHeight: '500px', overflow: 'auto' }" :placeholder="$t('common.pleaseSelect')" allowClear tree-default-expand-all :tree-data="departList" :field-names="fieldNames"></a-tree-select>
      </a-form-item>
      <a-form-item :label="$t('common.startState')">
        <a-select v-model:value="queryParam.status" :placeholder="$t('common.pleaseSelect')" allowClear>
          <a-select-option v-for="(item,index) in status" :value="item.value" :key="index">{{ item.label }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="loadData">{{$t('common.see')}}</a-button>
          <a-button @click="searchReset">{{$t('common.reset')}}</a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <CustomTable storeTableName="sysStaffList" rowKey="id" :loading="loading" :dataSource="dataSource" :columns="columns" :rowSelection="isEnvLocal?null:{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: checkboxProps, fixed: 'left'}" :pagination="ipagination" :scroll="{ x:1000,  y: showMore? 'calc(100vh - 446px)' : 'calc(100vh - 320px)'}" @change="handleTableChange" :operateMargin="true" :showMore="showMore">
      <template #operateLeft>
        <div class="operate-left">
          <a-button v-if="isEnvLocal" type="primary" @click="syncData(syncDataAry)">{{$t('common.sync')}}</a-button>
          <span v-else>
            <a-button v-if="hasPermission('system:user:add')" type="primary" @click="handleStaffAdd({},false)">{{$t('common.addNew')}}</a-button>
            <a-button ghost v-if="hasPermission('system:user:delete')" type="warning" :disabled="!selectedRowKeys.length" @click="handleDelete(null)">{{$t('common.delMore')}}</a-button>
          </span>
        </div>
      </template>
      <template #operateRight>
        <div class="slot-operate-right">
          <a-input-search v-model:value.trim="fuzzySearch" enter-button :placeholder="$t('basicData.jobNoName')" v-if="!showMore" @search="loadData" />
          <a-button class="ml-10" @click="toggleMore" type="primary" ghost>{{$t('common.highFilter')}}</a-button>
        </div>
      </template>
      <template #bodyCell="{ scope }">
        <template v-if="scope.column.key === 'staffNo'">
          <!--<span v-if="hasPermission('system:user:get')" class="code-link" @click="handleStaffDetail(scope.record)">{{scope.record.staffNo}} </span>-->
          <span>{{scope.record.staffNo}}</span>
        </template>
        <template v-else-if="scope.column.key === 'status'">
          <a-switch :checked="!Boolean(scope.record.status)" :disabled="scope.record.admin || ( !scope.record.admin && !hasPermission('system:user:edit')) || isEnvLocal" @change="(value) => changeStatus(value, {id: scope.record.id})" />
        </template> 
        <template v-else-if="scope.column.key === 'dept'">
          <span>{{scope.record.dept && scope.record.dept.name}}</span>
        </template>
        <template v-else-if="scope.column.key === 'roles'">
          <span>{{scope.record.roles && (scope.record.roles && scope.record.roles.map((item) => item.name).join()) || ' /'}}</span>
        </template>
        <template v-else-if="scope.column.key === 'operate'">
          <span class="table-operate-container">
            <span v-if="!scope.record.admin">
              <a-button type="link" class="primary-link" @click="setRole(scope.record)">{{$t('sysManage.setRole')}}</a-button>
              <a-divider type="vertical" />
              <a-button v-if="hasPermission('system:user:edit')" type="link" class="primary-link" @click="handleStaffAdd(scope.record,true)">{{$t('common.editor')}}</a-button>
              <a-divider type="vertical" />
              <a-button v-if="hasPermission('system:user:delete')" type="link" class="warning-link" :disabled="!Boolean(scope.record.status)" @click="handleDelete(scope.record.id)">{{$t('common.del')}}</a-button>
              <a-divider type="vertical" />
              <a-button type="link" class="primary-link" @click="resetPwd(scope.record)">{{$t('sysManage.resetPwd')}}</a-button>
            </span>
          </span>
        </template>
      </template>
    </CustomTable>
    <commone-modal ref="modalForm" tableName="sysStaff" :cloSapn="24" layout="vertical" :needChangeTitle="false" :modalTitle="$t('sysManage.setRole')" @ok="modalFormOk" :isUrlSave="true">
    </commone-modal>
    <SyncDataModal ref="syncDataModalRef" />
    <OperateStaff ref="OperateStaffRef" @ok="operateFun" />
  </div>
</template>

<script>
import { ListMixinPm } from '@/mixin/listMixinPm.js'
import { cloneDeep } from 'lodash'
import { store } from '@/store'
import { hasPermission, filterObj } from '@/utils'
import { mapState } from 'vuex'
import CommoneModal from '@/components/commonModal/normalModal.vue'
import { normalColumns, localColumns } from './modules/staffConfig'
import CustomTable from '@/components/commonTable/customTable.vue'
import SyncDataModal from '@/components/syncModal/syncDataModal.vue'
import OperateStaff from './modules/operateStaff.vue'
export default {
  name: 'sysStaff',
  mixins: [ListMixinPm],
  components: {
    CommoneModal,
    CustomTable,
    SyncDataModal,
    OperateStaff
  },
  data () {
    return {
      storeName: 'getUser',
      url: {
        list: '/api/system/user/list-fuzzy-by-page',
        delete: '/api/system/user/delete',
        changeStatus: '/api/system/user/changeStatus',
        resetPwd: '/api/system/user/resetPwd',
        sync: '/api/system/iot/sync-cloud-data'
      },
      columns: [],
      sexList: [
        { value: 0, label: this.$t('other.male') },
        { value: 1, label: this.$t('sysManage.female') },
        { value: 2, label: this.$t('sysManage.unknown') },
      ],
      postStatus: [
        { value: 0, label: this.$t('sysManage.onPos') },
        { value: 1, label: this.$t('sysManage.leavePos') },
      ],
      status: [
        { value: 0, label:  this.$t('common.start') },
        { value: 1, label: this.$t('common.stop') },
      ],
      fieldNames: { children: 'children', label: 'label', value: 'id' },
      fuzzySearchName: 'staffNo',
      syncDataAry: [
        { syncIotCloudDataType: 'ihs:system:user' }
      ]
    }
  },
  computed: {
    ...mapState({
      departList: (state) => state.normalData.departList,
      workTypeList: (state) => state.normalData.workTypeList,
      roleList: (state) => state.normalData.roleList,
      clientList: (state) => state.normalData.clientList,
      waterList: state => state.normalData.waterList,
    }),
  },
  methods: {
    hasPermission,
    getQueryParams () {
      let param = this.showMore ? cloneDeep(this.queryParam) : {}
      if (!this.showMore) param[this.fuzzySearchName] = this.fuzzySearch
      param.nickName = param.staffNo
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    handleStaffAdd(record,editable) {
      this.$refs.OperateStaffRef.initSelectOptions(this.initModalSelectOptions())
      this.$refs.OperateStaffRef.open(record,editable)
    },
    operateFun(){
      this.loadData()
    },
    handleStaffDetail (record) {
      this.$router.push({
        path: '/sysManage/staff/details',
        query: { id: record.id },
      })
    },
    resetPwd (record) {
      const params = {
        id: record.id,
        staffNo: record.staffNo,
      }
      this.confirmChangeStatus(this.url.resetPwd, params, this.$t('sysManage.sureResetPwd'))
    },
    setRole (record) {
      let roleIds = record.roles ? record.roles.map(i => i.id) : []
      this.handleEdit({ id: record.id, roleIds })
    },
    initModalSelectOptions () {
      return {
        roleIds: this.roleList,
        roleList: this.roleList,
        workTypeList: this.workTypeList,
        departList: this.departList,
        // clientList: this.clientList,
        waterList: this.waterList
      }
    },
  },
  async created () {
    this.columns = this.isEnvLocal ? localColumns : normalColumns
    await store.dispatch('getWater')
    store.dispatch('getDepart')
    store.dispatch('getWorkType')
    store.dispatch('getRole')
    // store.dispatch('getClient')
  },
}
</script>